/**
 * 
 */
package com.javass.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.config.TableConfiguration;

import com.javass.jdbc.impl.MysqlDatabaseComment;
import com.javass.jdbc.impl.OracleDatabaseComment;

/**
 * 帮助类
 * 
 * @author zhuguojie，zhu915139481@126.com
 * @date 2015年11月11日 下午4:34:07
 * @version 1.0
 */
public abstract class DatabaseCommentHelper {

	public static enum DatabaseType {
		oracle, mysql
	}

	private static Connection getConnection(JDBCConnectionConfiguration configuration) throws SQLException {
		Connection connection = DriverManager.getConnection(configuration.getConnectionURL(), configuration.getUserId(),
				configuration.getPassword());
		return connection;
	}

	public static DatabaseComment getDatabaseComment(IntrospectedTable introspectedTable) throws SQLException {
		return getDatabaseComment(introspectedTable.getContext().getJdbcConnectionConfiguration());
	}

	public static DatabaseComment getDatabaseComment(JDBCConnectionConfiguration configuration) throws SQLException {
		Connection connection = getConnection(configuration);
		DatabaseMetaData databaseMetaData = connection.getMetaData();
		String productName = databaseMetaData.getDatabaseProductName();
		if (productName.toLowerCase().contains(DatabaseType.mysql.toString())) {
			return new MysqlDatabaseComment(connection);
		} else if (productName.toLowerCase().contains(DatabaseType.oracle.toString())) {
			return new OracleDatabaseComment(connection);
		} else {
			throw new SQLException(String.format("the database %s dont support", productName));
		}
	}

	public static String getTableComment(IntrospectedTable introspectedTable) throws SQLException {
		DatabaseComment databaseComment = DatabaseCommentHelper.getDatabaseComment(introspectedTable);
		TableConfiguration configuration = introspectedTable.getTableConfiguration();
		return databaseComment.getTableComment(configuration.getCatalog(), configuration.getSchema(),
				configuration.getTableName());
	}

	public static String getColumnComment(IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn)
			throws SQLException {
		DatabaseComment databaseComment = DatabaseCommentHelper.getDatabaseComment(introspectedTable);
		TableConfiguration configuration = introspectedTable.getTableConfiguration();
		return databaseComment.getColumnComment(configuration.getCatalog(), configuration.getSchema(),
				configuration.getTableName(), introspectedColumn.getActualColumnName());
	}
}
